<template>
  <div class="view-fill">
    <div
      v-if="
        !detailInfo.visible &&
        !detailOtherStoreOrderInfo.visible &&
        !surgeryDetailInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="saveAndSubmit()" v-if="!id && $permission('receipt:saveAndSubmit')">保存并提交</el-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-payOrgName>
                <p>{{ userInfo.user.orgName }}</p>
              </template>
              <template v-slot:form-collectOrgName>
                <el-input
                  v-model="formInfo.data.collectOrgName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择供应商"
                >
                  <template #append>
                    <el-icon @click="selectSupplier"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-operator>
                <el-input
                  v-model="formInfo.data.operator"
                  :disabled="true"
                ></el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>附件信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏
              :image-field="formInfo.imageField"
             -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.refUplod"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldUploadList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-billAnnexPathList>
                <upload-img
                  v-model:value="formInfo.data.billAnnexPathList"
                  multiple
                  :action="action"
                  list-type="text"
                  title="发票附件"
                  :file-type="fileType"
                  :response-fn="handleResponse"
                />
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'关联信息'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-button>
                <el-button
                  :disabled="!formInfo.data.supplierId"
                  @click="getList"
                  >选择单据</el-button
                >
                <el-button
                  :disabled="!tableInfo.selections.length"
                  @click="remove"
                  >删除单据</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="false"
                  :check-box="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  class="table-scroll-hidden"
                  @handleEvent="tableInfoHandleEvent"
                >
                  <template v-slot:col-orderNo="scope">
                    <span
                      v-if="
                        $permission('receiving:detail') &&
                        scope.row.receivingType === 'receiving_order'
                      "
                      class="slip-edit"
                      @click="showDetail(scope.row)"
                      >{{ scope.row.orderNo || '-' }}</span
                    >
                    <span
                      v-else-if="scope.row.receivingType === 'other_store'"
                      class="slip-edit"
                      @click="showDetail(scope.row)"
                      >{{ scope.row.orderNo || '-' }}</span
                    >
                    <span
                      v-else-if="
                        $permission('surgeryAndTableReceipt:detail') &&
                        scope.row.receivingType === 'with_table_receiving_order'
                      "
                      class="slip-edit"
                      @click="showDetail(scope.row)"
                      >{{ scope.row.orderNo || '-' }}</span
                    >
                    <span
                      v-else-if="
                        scope.row.receivingType === 'with_table_receiving_order'
                      "
                      >{{ scope.row.orderNo || '-' }}</span
                    >
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
        <!-- 选择供应商 -->
        <SelectSupplier
          v-if="orgInfo.visible"
          :query="orgInfo.query"
          v-model:show-dialog="orgInfo.visible"
          :check-box="false"
          :highlight-row="true"
          @callback="callBackSupplier"
        />
        <select-order
          v-if="dialogInfo.visible"
          v-model:show-dialog="dialogInfo.visible"
          :query="dialogInfo.query"
          :other-query-list="queryList"
          @callback="selectOrderCallback"
        ></select-order>
      </NewFullScreen>
    </div>
    <other-store-order-detail
      v-if="detailOtherStoreOrderInfo.visible"
      :id="detailOtherStoreOrderInfo.id"
      v-model:visible="detailOtherStoreOrderInfo.visible"
    />
    <ReceivingOrderDetail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
    />
    <surgery-and-table-receipt-details
      v-if="surgeryDetailInfo.visible"
      :id="surgeryDetailInfo.id"
      v-model:visible="surgeryDetailInfo.visible"
    />
  </div>
</template>

<script setup name="purchTemplateModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import uploadImg from '@/components/UploadImg/index'
import {
  createReceiptBill,
  createReceiptBillAndSave,
  updateReceiptBill,
  recipetById,
  recipetReceivingOrderList,
} from '../../../api/receipt.js'
import PageFilter from '../../../components/PageFilter/index'
import SelectSupplier from '@/components/SelectSupplier/index'

import axios from 'axios'
import SelectOrder from '@/views/purch/receipt/selectOrder'
import ReceivingOrderDetail from './../../stock/receiving/detail'
import OtherStoreOrderDetail from '@/views/stock/otherStore/detail'
import SurgeryAndTableReceiptDetails from '@/views/stock/surgeryAndTableReceipt/detail'

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  id: {
    type: [String, Number],
  },
})

const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const fileType = ref(['jpg', 'png', 'pdf'])
const idMustIn = ref([])
const formRefs = ref([])
const formInfo = reactive({
  ref: null,
  refUplod: null,
  formRefs: [],
  data: {
    collectOrgId: '',
    collectOrgName: '',
    payOrgId: '',
    payOrgName: '',
    supplierId: '',
    billDate: '',
    receiveDate: '',
    billAmount: '',
    operator: '',
    remark: '',
    billCount: '',
    billSource: 1, //1 收到新增，2 供应商新增
    billAnnexPathList: [],
  },
  fieldList: [
    {
      label: '付款机构',
      value: 'payOrgName',
      type: 'slot',
      className: 'not-br',
    },
    { label: '收款机构', value: 'collectOrgName', type: 'slot' },
    {
      label: '发票号码',
      value: 'billNumber',
      type: 'input',
      labelTip: '输入的发票号码用“，”分隔',
      maxlength: 255,
    },
    {
      label: '票面金额',
      value: 'billAmount',
      type: 'money',
      unit: '元',
    },
    { label: '收票日期', value: 'receiveDate', type: 'date' },
    { label: '发票张数', value: 'billCount', type: 'input_number' },
    { label: '发票日期', value: 'billDate', type: 'date' },
    { label: '经办人', value: 'operator', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  fieldUploadList: [
    {
      label: '发票附件',
      value: 'billAnnexPathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    payOrgName: [
      { required: true, message: '请输付款机构', trigger: 'change' },
    ],
    billNumber: [
      {
        required: true,
        message: '请输入发票号码，用“，”分隔',
        trigger: 'blur',
      },
      {
        required: true,
        validator: proxy.$validate.validatChinese,
        target: 'blur',
      },
    ],
    collectOrgName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
    receiveDate: [
      { required: true, message: '请选择收票日期', trigger: 'change' },
    ],
    billCount: [
      {
        required: true,
        validator: proxy.$validate.positive,
        trigger: 'blur',
      },
    ],
    billAmount: [
      {
        required: true,
        validator: proxy.$validate.positiveMoney,
        target: 'blur',
      },
    ],
    // billAnnexPathList: [{type:'array',required : true, message: '请选择发票附件', trigger: 'blur'}],
  },
  labelWidth: '135px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
  },
  list: [
    { type: 'slot', value: 'button' },
    // { type: "button", label: "选择单据", event: getList },
    // { type: "button", label: "删除单据", event: remove }
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'billAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'slot' },
    { label: '供应商', value: 'supplierName' },
    { label: '入库日期', value: 'storeTime' },
    {
      label: '金额',
      value: 'billAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    // {label: '金额', value: 'billAmount', type: 'money', rules: {validator: proxy.$validate.positiveMoney, trigger: 'blur'}},
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: remove,
        show: true,
        popconfirmText: '删除后将改变数据,是否继续？',
      },
    ],
  },
})
const orgInfo = reactive({
  visible: false,
  query: {
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})

const queryList = reactive({
  //只关联收货单
  receiving_order: {
    idNotIn: [],
    idMustIn: [],
    sort: 'store_time desc',
  },
})
const dialogInfo = reactive({
  visible: false,
  query: {
    status: 3,
  },
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const detailOtherStoreOrderInfo = reactive({
  visible: false,
  id: '',
})
const surgeryDetailInfo = reactive({
  visible: false,
  id: '',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.data.length
})

const userInfo = computed(() => proxy.$store.state.user.userInfo)

watch(
  () => formInfo.data,
  (newName) => {
    newName.payOrgId = userInfo.value.user.orgId
    newName.payOrgName = userInfo.value.user.orgName
    newName.operator = userInfo.value.user.name
  },
  {
    immediate: true,
  }
)
onMounted(() => {
  if (props.id) {
    getRecipetById(props.id)
    getRecipetReceivingOrderList(props.id)
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref, formInfo.refUplod]
})

function tableInfoHandleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function getList() {
  queryList.receiving_order.idNotIn = []
  // queryList.other_store.idNotIn = []
  // queryList.with_table_receiving_order.idNotIn = []
  if (formInfo.data.supplierId) {
    tableInfo.data.forEach((item) => {
      if (item.receivingType) {
        queryList[item.receivingType].idNotIn.push(item.receivingId)
      }
    })
    dialogInfo.query.supplierId = formInfo.data.supplierId
    dialogInfo.visible = true
  } else {
    proxy
      .$confirm('请选择收款机构', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        selectSupplier()
      })
      .catch(() => {})
  }
}
function selectSupplier() {
  //选择供应商
  orgInfo.visible = true
}
function callBackSupplier(row) {
  //供应商返回
  if (row) {
    if (formInfo.data.collectOrgId !== row.supplierId) {
      tableInfo.data = []
    }
    formInfo.data.supplierId = row.supplierId
    formInfo.data.collectOrgId = row.supplierId
    formInfo.data.collectOrgName = row.supplierName
  }
}
function remove(selectRow) {
  if (selectRow && selectRow.id) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
    if (selectRow.receivingType === 'receiving_order') {
      queryList.receiving_order.idMustIn.push(selectRow.receivingId)
    } else if (selectRow.receivingType === 'other_store') {
      queryList.other_store.idMustIn.push(selectRow.receivingId)
    } else if (selectRow.receivingType === 'with_table_receiving_order') {
      queryList.with_table_receiving_order.idMustIn.push(selectRow.receivingId)
    }
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
        tableInfo.selections.forEach((item) => {
          if (item.receivingType === 'receiving_order') {
            queryList.receiving_order.idMustIn.push(item.receivingId)
          } else if (item.receivingType === 'other_store') {
            queryList.other_store.idMustIn.push(item.receivingId)
          } else if (selectRow.receivingType === 'with_table_receiving_order') {
            queryList.with_table_receiving_order.idMustIn.push(
              selectRow.receivingId
            )
          }
        })
      })
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!tableInfo.data.length) {
      proxy.$message({
        message: '关联信息不能为空',
        type: 'warning',
        showClose: true,
        duration: 3500,
      })
      return
    }
    const details = tableInfo.data.map((item) => {
      return {
        receivingId: item.receivingId ? item.receivingId : item.id,
        receivingType: item.receivingType,
      }
    })
    const data = formInfo.data
    data.billFilePath = data.billAnnexPathList.length
      ? data.billAnnexPathList.join(',')
      : ''
    data.details = details
    const api = data.id ? updateReceiptBill : isSaveAndSubmit === true ? createReceiptBillAndSave : createReceiptBill
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
        formInfo.ref.validateField()
      }
    })
  })
}
function getRecipetById(recipetId) {
  recipetById(recipetId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      formInfo.data.billAnnexPathList = resp.data.billAnnexPathList || []
      formInfo.data.supplierId = resp.data.collectOrgId
      formInfo.data.payOrgId = resp.data.payOrgId
      formInfo.data.payOrgName = resp.data.payOrgName
    }
  })
}
function getRecipetReceivingOrderList(recipetId) {
  let params = { billRegistrationId: recipetId }
  recipetReceivingOrderList(params).then((resp) => {
    if (resp && resp.success) {
      // tableInfo.data  = resp.data;
      tableInfo.data = resp.data.map((m) => {
        m.orderNo = m.receivingOrderVO.orderNo
        m.supplierName = m.receivingOrderVO.supplierName
        m.storeTime = m.receivingOrderVO.storeTime
        m.billAmount = m.receivingOrderVO.billAmount
        return m
      })
      props.idMustIn = Object.assign(
        [],
        resp.data.map((m) => m.receivingId)
      )
    }
  })
}
function handleResponse(response) {
  return response
}
function selectOrderCallback(data) {
  if (data && data.length) {
    tableInfo.data = tableInfo.data.concat(data)
    data.forEach((item) => {
      let idList = queryList[item.receivingType].idMustIn
      let index = idList.map((i, index) => {
        if (i.receivingId === item.receivingId) {
          return index
        }
      })
      if (index > -1) {
        idList.splice(index, 1)
      }
    })
  }
}
function showDetail(row) {
  if (row.receivingType === 'receiving_order') {
    detailInfo.id = row.receivingId
    detailInfo.visible = true
  } else if (row.receivingType === 'other_store') {
    detailOtherStoreOrderInfo.visible = true
    detailOtherStoreOrderInfo.id = row.receivingId
  } else if (row.receivingType === 'with_table_receiving_order') {
    surgeryDetailInfo.visible = true
    surgeryDetailInfo.id = row.receivingId
  }
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  height: 355px;
  display: flex;
  flex-direction: column;
}
</style>
